/*
 * @Descripttion:
 * @version:
 * @Author:
 * @Date: 2021-11-10 08:49:09
 */
import axios from 'axios'
import md5 from 'js-md5'
import { getLocalStore } from '@/config/global'
import { Notify } from 'vant'
// import router from '@/router'
// 创建 axios 请求
const service = axios.create({
  baseURL: process.env.VUE_APP_URL,
  timeout: 15000 // 设置超时时间
})

// 请求响应拦截 拦截 头
service.interceptors.request.use(
  config => {
    const timestamp = +new Date()
    const token = getLocalStore('token')
    const params = {
      'LPR-BRAND': 'Kredito',
      'LPR-TIMESTAMP': timestamp,
      'LPR-PLATFORM': 'h5',
      'Accept-Language': 'zh-CN'
    }
    const { advanced, ignoreAuth } = config
    config.headers['Content-Type'] = advanced
      ? 'application/x-www-form-urlencoded'
      : 'application/json; charset=utf-8'

    if (!ignoreAuth && token) {
      params.Authorization = token
      params['LPR-SIGNATURE'] = md5(md5(token + timestamp) + token)
    }
    config.headers = { ...config.headers, ...params }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  /* 响应体 错误时及时做一些提示 */
  response => {
    const res = response.data
    if (response.status !== 200 || res.code !== 0) {
      if (res.code === 100105) {
        // router.push({ path: '/login' })
        return
      }
      Notify({
        message: res.msg || 'Error',
        type: 'warning',
        duration: 5 * 1000
      })
      if (res.code === 50008 || res.code === 100200 || res.code === 100010) {
        Notify({
          type: 'warning',
          message: res.msg
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res.data
    }
  },
  error => {
    // console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)
export default service
